

document.write("<script type='text/javascript' src='"+GV.STATIC_JS+"gaopaiyi/qwebchannel.js?v="+GV.ver+"'></script>");
// document.write("<script type='text/javascript' src='"+GV.STATIC_JS+"gaopaiyi/socket.js?v="+GV.ver+"'></script>");

var socket = null,
    imgPathArray = new Array(),
    imageIndex;
globalCallback = null;

;(function (RCABase) {
    var gpy_init={
        extend: {
            baseUrl: "ws://127.0.0.1:12345",
            upload_Url: "/user/Asset/gaopaiyi?",
        },
        openSocket:function (Callback,messageCallback) {
            socket = new WebSocket(gpy_init.extend.baseUrl);
            socket.onopen = function () {
                new QWebChannel(socket, function (channel) {
                    window.dialog = channel.objects.dialog;
                    Callback(dialog)
                    gpy_init.sendPrintInfo(dialog, function (i,message) {
                        messageCallback(i,message)
                    })
                })
            };
            //连接发生错误的回调方法
            socket.onerror = function() {
                console.log("WebSocket连接发生错误");
            };
        },
        webSocketClose:function(){
            //因为我建立了多个socket，所以我需要知道我关闭的是哪一个socket，就做了一些判断。
            if (
                socket.readyState === 1 &&
                socket.url === "ws://1xx.xx.xx.xxx:8088/ws"
            ) {
                socket.close();//这句话是关键，之前我忘了写，一直没有真正的关闭socket
                console.log("对话连接已关闭");
            }
        },
        sendPrintInfo:function(dialog,callback){
            dialog.sendPrintInfo.connect(function (message) {
                // 返回信息
                gpy_init.sendPrintInfoMessage(message,function (i,message) {
                    callback(i,message)
                })
            })
        },
        sendPrintInfoMessage:function(message,callback){
            //读取二代证头像返回信息
            if (message.indexOf("IDcardInfo:") >= 0) {
                var value = message.substr(11);
                var values = value.split(" ");
                callback(0,values)
            }
            //读取二代证头像返回信息
            if(message.indexOf("idFaceInfo:") >= 0) {
                var value = message.substr(11);
                callback(1,"data:image/jpg;base64," + value)
            } else if(message.indexOf("fileBase64:") >= 0) {
                //获取文件base64返回值
                var value = message.substr(11);
                callback(1,value)
            }
            if (message.indexOf("idFaceFilepath:")>=0){
                var value = message.substr(15);
                callback(2,value)
            }
        },
        // 身份证信息
        getIcardData:function(Callback){
            gpy_init.openSocket(function () {
                dialog.get_functionTypes("getIdcardImage", "5", "", "");
            },function (i,GetIdCardData) {
                data = {};
                if (i==0){
                    data.empName = GetIdCardData[0];
                    data.empSexNmae = GetIdCardData[1];
                    data.empSex = GetIdCardData[1];
                    if(data.empSex){
                        if("男" == data.empSex){
                            data.empSex = 1;
                        }else{
                            data.empSex = 2;
                        }
                    }
                    data.empBirthday =GetIdCardData[3] + '-' + GetIdCardData[4] + '-' + GetIdCardData[5];
                    var birthday=  GetIdCardData[3] + '-' + GetIdCardData[4] + '-' + GetIdCardData[5];
                    var d = new Date();
                    //年龄
                    // data.extNum1 = d.getFullYear()-birthday.getFullYear()-((d.getMonth()<birthday.getMonth()|| d.getMonth()==birthday.getMonth() && d.getDate()<birthday.getDate())?1:0);
                    //身份证地址
                    data.empRegisteredPlace = GetIdCardData[6];
                    //身份证号
                    data.empIndentity = GetIdCardData[7];
                }else if (i==2) {
                    data.fileBase64 = GetIdCardData;
                }else {
                    data.fileBase64 = GetIdCardData;
                }
                Callback(i,data);
            })
        },

        // 文件拍照
        webSocketOpen:function(callback,messageCallback){
            // 文件
            socket = new WebSocket(gpy_init.extend.baseUrl);
            socket.onopen = function () {
                new QWebChannel(socket, function (channel) {
                    window.dialog = channel.objects.dialog;
                    callback(dialog)//点击事件
                    gpy_init.sendPrintInfoFile(dialog, function (i,message) {
                        messageCallback(i,message)
                    })
                })
            };
        },
        sendPrintInfoFile:function(dialog,msgCallback){
            // 返回信息
            dialog.sendPrintInfo.connect(function (message) {
                // 返回信息
                gpy_init.sendPrintInfoMessageFile(message,function (i,message) {
                    msgCallback(i,message)
                })
            })
        },
        // 消息
        sendPrintInfoMessageFile:function(message,msgCallback){
            console.log(message)
            if(message.indexOf("fileBase64:") >= 0) {
                //获取文件base64返回值
                var value = message.substr(11);
                msgCallback(1,value)
            }
            /********主头设备信息***********/
            //设备名
            if(message.indexOf("priDevName:") >= 0) {
                message = message.substr(11);
                console.log('设备名'+message);
                // message
                // var label = document.getElementById("lab1");
                // label.innerHTML = message;
            }
            //主头设备出图格式
            else if(message.indexOf("priModel:") >= 0) {
                // message = message.substr(9);
                // console.log(message);
                // var select = $("#priModelList");
                // if(message.indexOf("MJPG") >= 0)
                // {
                //     select.add(new Option(message), 0);
                // } else{
                //     select.add(new Option(message));
                // }
                // select.selectedIndex=0;
            }
            //主头设备分辨率
            else if(message.indexOf("priResolution:") >= 0) {
                message = message.substr(14);
                var select = $("#priResolutionList");
                select.append("<option>"+message+"</option>");
                // select.add(new Option(message));
                if($("#priResolutionList options").length > 3) {
                    select.val(2);//selectedIndex = 2;
                }
            }
            /********副头设备信息***********/
            //设备名
            else if(message.indexOf("subDevName:") >= 0)
            {
                message = message.substr(11);
                // var label = document.getElementById("lab2");
                // label.innerHTML = message;
            }
            //副头设备出图格式
            else if(message.indexOf("subModel:") >= 0)
            {
                message = message.substr(9);
                // var select = document.getElementById("subModelList");
                // if(message.indexOf("MJPG") >= 0)
                // {
                //     select.add(new Option(message), 0);
                // } else{
                //     select.add(new Option(message));
                // }
                // select.selectedIndex=0;
            }
            //副头设备分辨率
            else if(message.indexOf("subResolution:") >= 0)
            {
                message = message.substr(14);
                console.log('设备分辨率2 -- '+message);
                var select = $("#subResolutionList");
                select.append(new Option(message));
                if($("#subResolutionList option").length > 2)
                {
                    select.val(1);
                }
            }
            //后台程序返回设备序列号
            else if(message.indexOf("SerialNumber:") >= 0)
            {
                var SerialNumber = message.substr(13);
            }
            //后台程序条形码、二维码识别结果
            else if(message.indexOf("BarcodeInfo:") >= 0)
            {
                //格式为 "BarcodeInfo:" + "个数\n" + "识别结果\n"。每个每个结果后有换行符
                var BarcodeInfo = message.substr(12);
            }
            //图片保存后返回路径关键字savePhoto_success:
            else if(message.indexOf("savePhoto_success:") >= 0)
            {
                // imgPath = message.substr(18);
                // gpy_init.addImgDiv(imgPath);
            }
            //合成pdf成功，返回路径关键字composePDF_success:
            else if(message.indexOf("composePDF_success:") >= 0)
            {
                var path = message.substr(19);
                console.log(path);
                // removeAll();
                alert(path);
            }
        },
        sendChannel:function(input_selector,callback){
            gpy_init.webSocketOpen(function () {
                console.log('sendChannel---')
                //网页关闭函数
                window.onbeforeunload = function() {
                    dialog.get_actionType("closeSignal");
                }
                window.onunload = function() {
                    dialog.get_actionType("closeSignal");
                }
                $(document).on('click','#sendOrder',function () {
                    var order = $("#mingling").val();
                    if(!order)
                        return;
                    dialog.set_configValue(order);
                })
                // 切换视频
                $(document).on('change','#PriVideo_qh',function () {
                    //$(document).on('change','#closePriVideo_qh'),function(){
                    var i = $(this).val();
                    var label = $(this).data('lab');
                    if (i==1){
                        // 打开 视频 -1

                        $('#bigPriDev').css("display","block");
                        $('#shebei1').css("display","block");
                        dialog.devChanged("primaryDev_:" + label); // 打开主视频
                        dialog.devChanged("primaryDev_:" + label);
                        // 隐藏视频 - 2
                        $('#shebei2').css("display","none");
                        $('#bigSubDev').css("display","none");// 隐藏 视频 2
                        dialog.get_actionType("closeSubVideo");//关闭副视频

                    } else if (i==2) {
                        $('#bigSubDev').css("display","block");
                        $('#shebei2').css("display","block");
                        $('#shebei1').css("display","none");
                        $('#bigPriDev').css("display","none");// 1
                        dialog.devChanged("subDev_:"+label );// 打开副视频
                        dialog.get_actionType("closePriVideo");	// 打开主视频
                    }
                });
                //打开主视频
                $(document).on('click','#openPriVideo',function () {
                    var resolutionList = $("#priResolutionList");
                    // resolutionList.options.length = 0;
                    var modelList = $("#priModelList");
                    // modelList.options.length = 0;
                    var label1 = '设备1';
                    dialog.devChanged("primaryDev_:" + label1);
                });
                //主摄像头拍照按钮点击
                $(document).on('click','#photographPri',function () {
                    dialog.photoBtnClicked("primaryDev_");
                    dialog.get_actionType("savePhotoPriDev");
                });
                //副摄像头拍照按钮点击
                $(document).on('click','#photographSub', function() {
                    dialog.photoBtnClicked("subDev_");
                    dialog.get_actionType("savePhotoSubDev");
                });
                $(document).on('click','#setScanSize',function () {

                })
                //图像合成
                $(document).on('click','#imageBlend',function () {
                    dialog.get_actionType("imageBlend");
                });
                //获取文件base64
                $(document).on('click','#getFileBase64',function () {
                    dialog.get_functionTypes("getFileBase64","C:\\1234.pdf" , "","");
                    //dialog.get_functionTypes("getFileBase64","C:/1234.pdf" , "","");
                });
                //图片合成pdf
                $(document).on('click','#composePDF',function () {
                    console.log(imgPathArray)
                    if(imgPathArray.length > 0)
                    {
                        for (var i = 0; i < imgPathArray.length; i++)
                        {
                            //发送合成pdf图片的路径，第2个参数：图片文件路径，第3，第4个参数为空
                            var path = imgPathArray[i];
                            if(path.indexOf("file:///") >= 0)
                            {
                                path = path.substr(8);
                            }
                            console.log(path)
                            dialog.get_functionTypes("sendPDFImgPath", path, "","");
                        }
                        //发送合成pdf命令
                        //第2个参数：保存路径，如果该路径不存在则保存在.exe文件下的eloamFile文件夹
                        //第3个参数：保存文件名称，如果为空则按照当前时间命名，
                        //第4个参数为图片质量1-100的十进制整数x（以x:1保存）100最好
                        //dialog.get_functionTypes("composePDF", "C:" , "1234", "75");
                        //dialog.get_functionTypes("composePDF", "C:" , "12345650", "50");
                        dialog.get_functionTypes("composePDF", "D:/gpy/eloamPhoto" , "12345100", "100");
                    }
                });
                //删除本地文件
                $(document).on('click','#deleteFile',function () {
                    //dialog.get_functionTypes("deleteFile", "C:\\Users\\Administrator\\Desktop\\eloamPhoto\\20180903-200102046.jpg", "", "");
                    //dialog.get_functionTypes("deleteFile", "C:/Users/Administrator/Desktop/eloamPhoto/eeee.jpg", "", "");
                    for (var i = 0; i < imgPathArray.length; i++)
                    {
                        //删除文件，第2个参数：图片文件路径，第3，第4个参数为空
                        var path = imgPathArray[i];
                        if(path.indexOf("file:///") >= 0)
                        {
                            path = path.substr(8);
                        }
                        dialog.get_functionTypes("deleteFile", path, "", "");
                    }
                    removeAll();
                });
                //接收图片流用来展示，多个，较小的base64，主头数据
                dialog.send_priImgData.connect(function(message) {
                    var element = $("#bigPriDev");
                    element.attr('src',"data:image/jpg;base64," + message);
                });
                //接收图片流用来展示，多个，较小的base64，副头数据
                dialog.send_subImgData.connect(function(message) {
                    var element = $("#bigSubDev");
                    element.attr('src',"data:image/jpg;base64," + message);
                });

                //接收拍照base64，主头数据
                dialog.send_priPhotoData.connect(function(message) {
                    var element = $("#devPhoto");
                    var src = "data:image/jpg;base64,"+message;
                    element.attr('src',"data:image/jpg;base64,"+message);
                    $(input_selector + '-preview').attr('src',"data:image/jpg;base64,"+message);
                    gpy_init.addImgDiv(src);
                    callback(src)
                });
                //接收拍照base64，副头数据
                dialog.send_subPhotoData.connect(function(message) {
                    var element = $("#devPhoto");
                    var src = "data:image/jpg;base64,"+message;
                    element.attr('src',"data:image/jpg;base64,"+message);
                    callback(src)
                });

                console.log("加载视频开始 ready to send/receive messages!");
                //网页加载完成信号
                //dialog.html_loaded("two");
                dialog.html_loaded("faceDetect_two");
                dialog.set_configValue("set_savePath:D:/gpy/eloamPhoto");//设置图片默认地址
                //设置图片dpi，第二个参数是dpi大小
                dialog.get_functionTypes("setImageProperty", "300", "", "");
                //关闭 副头
                dialog.get_actionType("closeSubVideo");
            },function (i,message) {

                console.log('----消息-------')
            })
        },
        senduploadFile:function(url,path_file,container,callback){
            $.ajax({
                url: url,
                type: 'post',
                data:{path:path_file,pathbase64:container},
                success: function (data) {
                    if (data.code==1){
                        callback(data.data)
                    } else {

                    }
                    callback(data)
                }
            })
        },
        //增加图片缩略图
        addImgDiv:function(imgPath){
            var container =document.getElementById('container');
            var newchild = document.createElement("div");
            newchild.setAttribute("style", "float:left");
            imgPath = "" + imgPath ;//   file:///D:/20200728-134829112.jpg
            newchild.setAttribute("id", imgPath);
            imgPathArray.push(imgPath);  //增加缩略图时默认把路径加入图片数组
            newchild.innerHTML = "" +
                "<img  width='105' height='85' src='"+imgPath+"' onclick='init_gpy.lookLayerImg(this)' /></img>" +
                "<input type='checkbox' checked='checked'  class='imgPath' onchange='init_gpy.checkboxClicked(this)' value='"+imgPath+"'/>";
            container.appendChild(newchild);
        },
        //清空缩略图
        removeAll:function  (){
            $('#container').html();
            imgPathArray = [];
        },
        checkboxClicked:function(checkboxItem){
            if(imgPathArray.indexOf(checkboxItem.parentNode.id) < 0)
            {
                imgPathArray.push(checkboxItem.parentNode.id);
            } else{
                var index = imgPathArray.indexOf(checkboxItem.parentNode.id);
                imgPathArray.splice(index, 1);
            }
        },
        openUploadDialog:function(obj,callback){
            console.log(obj)
            var params = '&path=' + obj.path +'&PathArray=';//+ '&multi=' + multi + '&filetype=' + filetype + '&app=' + app;
            layer.open({
                type: 2,
                icon: 4,
                title: obj.title,
                anim: 2,
                area: ['1050px', '700px'],
                content: gpy_init.extend.upload_Url+ 'type='+obj.type+'&path=' + obj.path ,
                success: function (layero, index) {
                    var iframe = window['layui-layer-iframe' + index];//拿到iframe元素
                    iframe.child(obj)//向此iframe层方法 传递参数
                },
                cancel: function (index, layero) {//取消事件
                    console.log('取消事件')
                    // gpy_init.webSocketClose()
                },
                end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                    console.log('关闭事件')
                    // gpy_init.webSocketClose()
                }
            });

        },
        ajaxLayerIframeOpen: function (PathArray,title, html, area) {
            layer.open({
                type: 2,
                icon: 4,
                title: title,
                anim: 2,
                area: area,
                content: html,
                success: function (layero, index) {
                    var iframe = window['layui-layer-iframe' + index];//拿到iframe元素
                    iframe.child(PathArray)//向此iframe层方法 传递参数
                },
                cancel: function (index, layero) {//取消事件
                    console.log('取消事件')
                    // gpy_init.webSocketClose()
                },
                end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                    console.log('关闭事件')
                    // gpy_init.webSocketClose()
                }
            });
        },
        lookLayerImg:function(img) {
            layer.photos({
                photos: {
                    "title": "", //相册标题
                    "id": 'image_preview', //相册id
                    "start": 0, //初始显示的图片序号，默认0
                    "data": [   //相册包含的图片，数组格式
                        {
                            "alt": "",
                            "pid": 666, //图片id
                            "src": img, //原图地址
                            "thumb": img //缩略图地址
                        }
                    ]
                } //格式见API文档手册页
                , anim: 5, //0-6的选择，指定弹出图片动画类型，默认随机
                shadeClose: true,
                // skin: 'layui-layer-nobg',
                shade: [0.5, '#000000'],
                shadeClose: true,
            })

        },
    };

    RCABase.init_gpy = gpy_init
})(RCABase)

